/**
 * 登录日志控制器 / 登录日志控制器分页查询
 * @param {options} data
 * @param {string} [data.url] 下载地址
 * @param {string} [data.method] 请求方式
 * @param {object} [data.params] 请求参数
 * @param {string} [data.fileName] 下载名称
 * @param {import("axios").AxiosRequestConfig} [config]
 */
import axios from "../api/request";

export default (options) => {
  const { url, method = "get", params, fileName = "" } = options;
  const config = {
    url,
    method,
    responseType: "blob",
  };
  if (method === "get") {
    config["params"] = params;
  } else {
    config["data"] = params;
    config["params"] = params;
  }
  return new Promise((resolve, reject) => {
    axios(config)
      .then((res) => {
        let userFileName = "";
        if (!fileName) {
          userFileName = res.headers["content-disposition"].split("filename=")[1];
          if (userFileName && userFileName.includes('"')) userFileName = userFileName.slice(1, -1);
        } else {
          userFileName = fileName;
        }
        userFileName = decodeURI(userFileName);
        // 文件格式
        const contentType = res["type"];
        const blob = new Blob([res.data], { type: contentType }); //指定格式为vnd.ms-excel
        const downloadElement = document.createElement("a");
        const href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = !userFileName ? Date.now().toString() : userFileName; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
        resolve(res);
      })
      .catch(function (error) {
        console.log(error);
        return reject(error);
      });
  });
};
